package cn.support.neo.mvp.core.service.client;


import android.content.Context;

import com.github.pwittchen.prefser.library.Prefser;

import cn.support.neo.mvp.BuildConfig;
import cn.support.neo.mvp.core.provider.OkHttpClientProvider;
import cn.support.neo.mvp.core.provider.TokenProvider;
import cn.support.neo.mvp.core.service.progress.ProgressListener;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Name:网络访问服务
 * Author: WK（wangkun@xjzhicheng.com)
 * Date: 2016-06-30
 * Describe: PLEASE TO FIXME...
 */
public class RetrofitClient implements HttpClient<Retrofit> {

    private Context context;
    private Prefser prefser;
    private TokenProvider tokenProvider;
    private ProgressListener progressListener;

    public RetrofitClient(Context context, Prefser prefser) {
        this(context, prefser, null);
    }

    public RetrofitClient(Context context, Prefser prefser, ProgressListener progressListener) {
        this.context = context;
        this.prefser = prefser;
        this.progressListener = progressListener;
    }

    @Override
    public Retrofit getHttpClient() {
        return new Retrofit.Builder()
                .baseUrl(BuildConfig.ENDPOINT)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(createOkHttpClient(prefser))
                .build();
    }

    @Override
    public void setToken(TokenProvider tokenProvider) {
        this.tokenProvider = tokenProvider;
    }


    private OkHttpClient createOkHttpClient(Prefser prefser) {
        if (progressListener != null) {
            return OkHttpClientProvider.getProgressInstance(context, prefser, tokenProvider, progressListener);
        } else {
            return OkHttpClientProvider.getInstance(context, prefser, tokenProvider);
        }
    }


}
